package com.cf.end.school;

import com.cf.core.player.Player;
import com.cf.core.player.impl.DefaultUserInfo;
import com.cf.core.player.impl.DefaultWebSocketPlayer;
import com.cf.game.constant.SysConstant;
import com.cf.game.message.BeatRequest;
import com.cf.game.message.SchoolMessageRegister;
import com.cf.game.service.pojo.UserInfo;
import com.cf.game.service.service.UserInfoService;
import com.cf.game.service.util.ObjectJsonUtil;
import com.cf.game.service.util.RedisContants;
import com.cf.game.service.util.StringUtils;
import com.cf.game.stage.ClassRoomManager;
import com.cf.game.stage.MatchStage;
import com.cf.serialize.MessageConvertService;
import com.cf.serialize.Request;
import com.cf.serialize.common.CommonMessageRegister;
import com.cf.serialize.common.LoginResponse;
import com.cf.serialize.common.StartRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

import javax.annotation.PostConstruct;
import javax.websocket.Session;
import java.io.IOException;

/**
 * websocket-BizssEndPoint
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/2/28 10:58
 */


@Component("school")
public class SchoolEndPoint {

    private Logger logger = LoggerFactory.getLogger(SchoolEndPoint.class);

    @Autowired
    private JedisCluster jedisCluster;

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private ClassRoomManager classRoomManager;

    private MessageConvertService messageService = new MessageConvertService();

    @Autowired
    private SchoolMessageRegister schoolMessageRegister;

    @Autowired
    private CommonMessageRegister commonMessageRegister;

    private MatchStage matchStage = new MatchStage(10, Integer.MAX_VALUE, "match-stage", SysConstant.partitionNum);

    @PostConstruct
    public void init() {
        schoolMessageRegister.register(messageService);
        commonMessageRegister.register(messageService);
    }

    /**
     * 连接建立成功调用的方法
     */
    public void onOpen(Session session) {
        logger.info("onOpen");
        session.setMaxIdleTimeout(1200 * 1000l);
    }

    /**
     * 连接关闭调用的方法
     */
    public void onClose(Session session) {
        logger.info("close");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    public void onMessage(String message, Session session) throws IOException {
        logger.info("接收到消息【{}】,开始进行处理！", message);
        Request serializeMsg = messageService.serialize(message);
        UserInfo userInfo = checkUser(serializeMsg);
        if (userInfo == null) {
            session.getAsyncRemote().sendText(ObjectJsonUtil.toString(new LoginResponse()));
            return;
        }

        //处理匹配请求
        if (serializeMsg instanceof StartRequest) {
            //处理Start请求
            Player player = createPlayer(userInfo, serializeMsg, session);
            matchStage.getMatchTicketAndJoinQueue(player);
            return;
        }

        //处理打击请求
        if (serializeMsg instanceof BeatRequest) {
            //处理Start请求
            classRoomManager.dispatchMessage((BeatRequest) serializeMsg);
            return;
        }

        logger.warn("当前消息不知道怎么处理！【{}】", message);

    }

    private Player createPlayer(UserInfo userInfo, Request serializeMsg, Session session) {
        DefaultUserInfo defaultUserInfo = new DefaultUserInfo(userInfo.getId(), serializeMsg.getUserToken(), userInfo.getDefaultName(), userInfo.getDefaultHeadImg());
        DefaultWebSocketPlayer defaultWebSocketPlayer = new DefaultWebSocketPlayer(session, defaultUserInfo);
        return defaultWebSocketPlayer;
    }

    private UserInfo checkUser(Request serializeMsg) {
        if (!StringUtils.hasLength(serializeMsg.getUserToken())) {
            return null;
        }
        Integer userId = getUserIdFromRedis(serializeMsg.getUserToken());
        if (userId != null)
            return userInfoService.selectUserNameAndUserImg(userId);
        return null;
    }

    public void onError(Session session, Throwable error) {
        logger.info("onError");
        error.printStackTrace();
    }

    public Integer getUserIdFromRedis(String token) {
        String s = jedisCluster.get(RedisContants.LOGIN_KEY + token);
        if (StringUtils.hasLength(s))
            return Integer.valueOf(s);
        else
            return null;
    }

}
